package elcom.control.outputter;

import java.util.ArrayList;
import java.util.Iterator;

import elcom.model.common.Log;
import elcom.model.data.QueueIO;

public class Outputter extends Thread {

	private QueueIO<String> queOut = null;
	private ArrayList<String> lstValue = new ArrayList<>();

	public Outputter(QueueIO<String> queueOut) {
		this.queOut = queueOut;
	}

	@Override
	public void run() {
		while (true) {
			try {
				if (queOut.size() >= 200)
					synchronized (queOut) {
						while (queOut.size() >= 200) {
							writeData();
						}
					}
				else {
					writeData();
				}
				synchronized (queOut) {
					queOut.wait(60000);
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.logErr(e.toString());
			}
		}
	}

	private void writeData() {
		Iterator<String> ite = queOut.iterator();
		while (ite.hasNext()) {
			if (lstValue.size() >= 200) {
				break;
			}
			String value = ite.next();
			lstValue.add(value);
		}
		WriteResult.writefile(lstValue);
		for (int i = 0; i < lstValue.size(); i++) {
			String value = lstValue.get(i);
			queOut.remove(value);
		}
		lstValue.clear();
	}
}
